#include "plugins.h"


#define JSON_COMPONENTS_PATH				"component"
#define INDEX_TAG						":"
#define JSON_ITEM						256

CPlugins::CPlugins(void)
{
	m_pdata.dispose();
}
CPlugins::~CPlugins(void)
{

}

HRESULT CPlugins::LoadMemory(LPCSTR pMemory)
{
	m_pJson = cJSON_Parse(pMemory);
	return 	LoadPluginModule(m_pJson);
}
DWORD CPlugins::GetClsidCount()
{
	return m_SortVecPlugins.size();
}

DWORD CPlugins::GetCompentsCount()
{
	return m_mapComponents.size();
}

DWORD CPlugins::LoadCompents(ComponentPlugin& mapCompents)
{
	mapCompents.clear();
	mapCompents = m_mapComponents;
	return mapCompents.size();
}

DWORD CPlugins::LoadClsidAll(PluginVector& vecPlugins)
{
	DWORD dwCount = GetClsidCount();
	
	vecPlugins.clear();

	for (UINT uloop = 0; uloop < dwCount; uloop++)
	{	
		vecPlugins.push_back_sort(m_SortVecPlugins[uloop]);
	}

	return vecPlugins.size();
}
DWORD CPlugins::LoadClsid(PluginVector& vecPlugins,const char* pComponents)
{
	DWORD dwCount = GetClsidCount();

	vecPlugins.clear();

	for (UINT uloop = 0; uloop < dwCount; uloop++)
	{	
		if (string_stricmp(pComponents,m_SortVecPlugins[uloop].szComponent.c_str()) == 0)
		{
			vecPlugins.push_back(m_SortVecPlugins[uloop]);
		}
	}
	return vecPlugins.size();
}

HRESULT CPlugins::LoadPluginModule(const cJSON* JsRoot)
{
	HRESULT hr = S_OK;
	
	if (IsJsonObject(JsRoot))
	{
		cJSON* JsModule = cJSON_GetObjectItem(JsRoot, JSON_COMPONENTS_PATH);
		
		if(IsJsonArray(JsModule))
		{
			int iloop = 0;
			for(iloop = 0; iloop < cJSON_GetArraySize(JsModule); iloop++)   
			{
				cJSON* JsItem = cJSON_GetArrayItem(JsModule, iloop);

				if (IsJsonString(JsItem))
				{
					LoadPluginItem(JsItem);
				}
			}
		}
	}

	return hr;
}

HRESULT CPlugins::LoadPluginItem(const cJSON* JsRoot) 
{
	HRESULT hr = S_OK;

	if (IsJsonString(JsRoot))
	{
		CharArrayPtr item;
		item.dispose();
		item = ALLOC_NEW char[JSON_ITEM + 1]();
		rc_assert(item.m_p != NULL, E_FAIL)

		const char* value = JsRoot->valuestring;
		rc_assert(value != NULL, E_FAIL)

		s_strcpy(item, JSON_ITEM, value);

		char* next = NULL;
		char* clsid = NULL;
		char* component = NULL;
		char* index = NULL;
		char* off = NULL;

		clsid	= s_strtok(item, INDEX_TAG, &next);
		rc_assert(clsid != NULL, E_FAIL)

		component = s_strtok(NULL, INDEX_TAG, &next);
		rc_assert(component != NULL, E_FAIL)

		index	= s_strtok(NULL, INDEX_TAG, &next);
		rc_assert(index != NULL, E_FAIL)

		off = s_strtok(NULL, INDEX_TAG, &next);
		rc_assert(off != NULL, E_FAIL)

		m_mapComponents[component] = off;
		m_SortVecPlugins.push_back(Com_Plugin(StringToGUID(clsid),atol(index),component));
	}

	return hr;
}

HRESULT CPlugins::GetItemString(const cJSON* JsRoot,const char* id,char** pItem)
{
	HRESULT hr  = E_FAIL;

	if (IsJsonObject(JsRoot))
	{
		cJSON* JsItem = cJSON_GetObjectItem(JsRoot,id);

		if (IsJsonString(JsItem))
		{
			*pItem = JsItem->valuestring;
			hr = S_OK;
		}
	}
	return hr;
}
